<template>
  <div
    v-show="isVisible && isMounted"
    class="bg-white rounded-xl shadow-sm overflow-hidden mt-6"
  >
    <!-- 头部区域 -->
    <div class="p-6 border-b border-gray-100">
      <div class="flex justify-between items-center">
        <div class="flex items-center">
          <div class="p-2 bg-blue-50 rounded-lg">
            <i class="ri-code-box-line text-xl text-blue-500"></i>
          </div>
          <h3 class="text-xl font-semibold text-gray-800 ml-3">
            代码预览
          </h3>
        </div>
        <div class="flex gap-3">
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
            @click="copyCode"
          >
            <i class="ri-file-copy-line mr-2 text-lg" />
            复制代码
          </button>
          <button 
            class="inline-flex items-center px-4 py-2 text-sm font-medium text-green-600 bg-green-50 rounded-lg hover:bg-green-100 transition-colors duration-200"
            @click="downloadCode"
          >
            <i class="ri-download-line mr-2 text-lg" />
            下载代码
          </button>
        </div>
      </div>
    </div>

    <!-- 代码预览区域 -->
    <div class="overflow-auto max-h-[800px]">
      <div class="p-6">
        <div class="code-preview bg-gray-50 rounded-lg" ref="codeContainer">
          <pre class="line-numbers"><code class="language-javascript">{{ props.codeContent }}</code></pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import { useClipboard } from '../../composables/useClipboard';
import Prism from 'prismjs';
import 'prismjs/themes/prism.css';
import 'prismjs/plugins/line-numbers/prism-line-numbers.css';
import 'prismjs/plugins/line-numbers/prism-line-numbers';

const props = defineProps({
  codeContent: {
    type: String,
    required: true
  },
  isVisible: {
    type: Boolean,
    default: true
  },
  fileName: {
    type: String,
    default: 'generated_code'
  }
});

const emit = defineEmits(['copy-success', 'copy-error', 'download-success', 'download-error']);
const isMounted = ref(false);
const codeContainer = ref(null);
const { copyToClipboard } = useClipboard();

// 高亮代码的方法
const highlightCode = () => {
  if (codeContainer.value) {
    // 自定义 4gl 语言的语法规则
    Prism.languages['javascript'] = Prism.languages['javascript'] || {};
    Prism.languages['javascript'].comment = [
      {
        pattern: /^#.*/gm,  // 匹配以 # 开头的整行
        color: '#0D9488'    // 设置为绿色
      },
      {
        pattern: /\/\/.*/,  // 保持原有的 // 注释规则
        color: '#0D9488'
      }
    ];
    
    Prism.highlightElement(codeContainer.value.querySelector('code'));
  }
};

// 监听代码内容变化
watch(() => props.codeContent, () => {
  nextTick(() => {
    highlightCode();
  });
});

// 监听可见性变化
watch(() => props.isVisible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      highlightCode();
    });
  }
});

const copyCode = async () => {
  const success = await copyToClipboard(props.codeContent);
  if (success) {
    emit('copy-success');
  } else {
    emit('copy-error');
  }
};

const downloadCode = () => {
  const blob = new Blob([props.codeContent], { type: 'text/plain' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `${props.fileName}.4gl`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
  emit('download-success');
};

onMounted(() => {
  nextTick(() => {
    isMounted.value = true;
    highlightCode();
  });
});
</script>

<style scoped>
/* 自定义滚动条样式 */
.overflow-auto {
  scrollbar-width: thin;
  scrollbar-color: #E5E7EB transparent;
}

.overflow-auto::-webkit-scrollbar {
  width: 10px !important;
  height: 10px !important;
}

.overflow-auto::-webkit-scrollbar-track {
  @apply bg-gray-100 rounded-full;
}

.overflow-auto::-webkit-scrollbar-thumb {
  @apply bg-gray-300 rounded-full;
  border: 2px solid transparent;
  background-clip: padding-box;
  min-height: 40px;
}

.overflow-auto::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-400;
}

/* 代码预览容器样式 */
.code-preview {
  position: relative;
  background-color: #f9fafb;
  border-radius: 0.5rem;
}

/* 基础代码块样式 */
:deep(pre[class*="language-"]) {
  margin: 0;
  padding: 1rem 1rem 1rem 3.8rem !important;
  background-color: transparent;
  overflow: visible;
  min-height: 100%;
}

/* 行号容器样式 */
:deep(.line-numbers-rows) {
  position: absolute;
  top: 1rem;
  bottom: 1rem;
  left: 1rem;
  width: 2.5rem !important;
  border-right: 1px solid #E5E7EB;
  pointer-events: none;
  user-select: none;
  font-size: 14px;
  line-height: 1.6;
  padding-right: 0.5rem;
  height: calc(100% - 2rem);
}

/* 行号样式 */
:deep(.line-numbers-rows > span) {
  display: block;
  counter-increment: linenumber;
  color: #9CA3AF;
  text-align: right;
  height: 1.6em;
}

:deep(.line-numbers-rows > span::before) {
  content: counter(linenumber);
  display: block;
  padding-right: 0.8rem;
}

/* 代码内容样式 */
:deep(code[class*="language-"]) {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  line-height: 1.6;
  tab-size: 4;
  white-space: pre;
  word-spacing: normal;
  word-break: normal;
  display: block;
  min-height: 100%;
}

/* 确保代码内容不会与行号重叠 */
:deep(.line-numbers.line-numbers) {
  position: relative;
  padding-left: 3.8rem;
  counter-reset: linenumber;
  min-height: 100%;
}

:deep(.line-numbers .line-numbers-rows) {
  position: absolute;
  pointer-events: none;
  top: 0;
  font-size: 100%;
  left: -3.8rem;
  width: 3rem;
  letter-spacing: -1px;
  border-right: 1px solid #E5E7EB;
  user-select: none;
  height: 100%;
}

/* 代码高亮主题配色 - 调整后的配色方案 */
:deep(.token.comment) {
  color: #16A34A !important; /* 注释：深绿色 */
}

:deep(.token.function) {
  color: #8B5CF6 !important; /* 函数：紫色 */
}

:deep(.token.keyword) {
  color: #0284C7 !important; /* 关键字：深蓝色 */
}

:deep(.token.string) {
  color: #EA580C !important; /* 字符串：橙色 */
}

:deep(.token.number) {
  color: #0891B2 !important; /* 数字：青色 */
}

:deep(.token.operator) {
  color: #16A34A !important; /* 操作符：深绿色 */
}

:deep(.token.punctuation) {
  color: #16A34A !important; /* 标点符号：深绿色 */
}

:deep(.token.property) {
  color: #8B5CF6 !important; /* 属性：紫色 */
}

:deep(.token.constant) {
  color: #0284C7 !important; /* 常量：深蓝色 */
}

:deep(.token.class-name) {
  color: #0891B2 !important; /* 类名：青色 */
}

:deep(.token.boolean) {
  color: #0284C7 !important; /* 布尔值：深蓝色 */
}

/* 确保水平滚动正常工作 */
.overflow-auto {
  overflow-x: auto !important;
  overflow-y: auto !important;
}

/* 调整水平滚动条样式 */
.overflow-auto::-webkit-scrollbar {
  height: 6px !important;
  width: 6px !important;
}

/* 代码背景和行号样式 */
:deep(pre[class*="language-"]) {
  background-color: #FFFFFF !important;
  color: #24292F !important;
}

:deep(.line-numbers-rows) {
  border-right: 1px solid #E5E7EB !important;
  background-color: #F8F9FA !important;
}

:deep(.line-numbers-rows > span::before) {
  color: #6E7781 !important;
}

/* 代码容器样式 */
.code-preview {
  background-color: #FFFFFF !important;
  border: 1px solid #E5E7EB !important;
  border-radius: 0.5rem;
  overflow: hidden;
}

/* 选中文本的样式 */
:deep(pre[class*="language-"])::selection,
:deep(pre[class*="language-"]) ::selection,
:deep(code[class*="language-"])::selection,
:deep(code[class*="language-"]) ::selection {
  background: #ADD6FF !important; /* 浅蓝色选中背景 */
  color: #24292F;
}

/* 代码块内的滚动条样式 */
:deep(pre[class*="language-"])::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

:deep(pre[class*="language-"])::-webkit-scrollbar-track {
  background: #F8F9FA;
}

:deep(pre[class*="language-"])::-webkit-scrollbar-thumb {
  background: #D0D7DE;
  border-radius: 5px;
}

:deep(pre[class*="language-"])::-webkit-scrollbar-thumb:hover {
  background: #A8B3BD;
}

/* 特别处理以 # 开头的行 */
:deep(code[class*="language-"] > span:first-child) {
  color: #0D9488 !important;
}
</style>